<template>
  <div id="search-content">
        <!-- 搜索栏 -->
        <form action="/">
            <van-search
            v-model="searchText"
            placeholder="请输入搜索关键词"
            show-action
            @search="onSearch(searchText)"
            @cancel="$router.back()"
            @focus="isResultShow=false"
            />
        </form>
         <!-- 搜索结果 -->
        <search-result
        v-if="isResultShow"
        :search-text="searchText"
        />
        <!-- 联想建议 -->
         <search-suggestion
          v-else-if="searchText"
         :search-text="searchText"
         @search="onSearch"
         />
        <!-- 历史记录 -->
        <search-history
        v-else
        :search-histories="searchHistory"
        @search="onSearch"
        @updata-history="searchHistory=$event"
        />
  </div>
</template>
<script>
import searchSuggestion from './components/search-suggestion.vue'
import searchHistory from './components/search-history.vue'
import searchResult from './components/search-result.vue'
import {getSearchHistory} from '@/api/search.js'
import {mapState} from 'vuex'
import {setItem,getItem} from "@/utils/storage.js"
export default {
  name: 'search',
  components: {
    searchSuggestion,
    searchHistory,
    searchResult
  },
  directives: {},
  computed:{
     ...mapState(['user'])
  },
 created(){
    this.loadSearchHistories()
  },
  data() {
    return {
       searchText:'',//搜索输入框的内容
       isResultShow:false ,//控制搜索结果的状态
       searchHistory:[],//搜索历史数据
    };
  },
  watch:{
    //监视搜索历史记录的变化，存储到本地存储  同一监视searchHistory的变化
    searchHistory(){
      setItem('search-historys',this.searchHistory)
    }
  },
  mounted() {

  },
  methods: {
    onSearch(searchText){
      //把输入框设置为你要搜索的文本
      this.searchText=searchText

      //记录搜索历史记录
      const index=this.searchHistory.indexOf(searchText)
      if(index!==-1){
          this.searchHistory.splice(index,1)
      }
      this.searchHistory.unshift(searchText)
       //如果用户已登录，则把搜索历史记录存储到线上
        //  if(user){
        //    const {data} = await getSearchHistory()
        //    this.searchHistory=data
        //  }
         //提示：只要我们调用获取搜索结果的数据接口，后端会帮我们自动存储用户的搜索历史记录
       //如果没有登录，则把搜索历史记录存储到本地

      //setItem('search-historys',this.searchHistory)

      //展示搜索结果
      this.isResultShow=true
    },
    async loadSearchHistories(){
      //因为后端帮我们存储的搜索数据太少了 与本地进行合并
      let localHistories=getItem('search-historys') || []//本地
      if(this.user){
          const {data} = await getSearchHistory()//线上
          console.log(data.data.keywords)
          //合并数组 [...数组,...数组]
          //把Set转为数组[...Set对象]
          //数组去重 [...new Set([...数组,...数组])]
         localHistories=[...new Set([...localHistories,...data.data.keywords])]
      }
      this.searchHistory=localHistories
    }
  },
};
</script>
<style lang="less" scoped>

</style>
